'use strict'

const titbit = require('titbit');

const {cookie,session} = require('titbit-toolkit')

const app = new titbit({
    debug:true
})

app.use( (new cookie()).mid() )

//session是基于cookie的，一定要在cookie之后
app.use( (new session()).mid() )

//cookie
app.use(async (c,next)=>{
    if(c.headers['cookie'] === undefined){
        c.setHeader('set-cookie','key=1234')
    }
    await next()
})

app.use(async (c,next)=>{
    console.log('just for home')
    await next()
    //添加只针对home分组执行的中间件
},{group:'home'})

//@home表示是分组，home表示是名字
app.get('/',async c=>{
    c.res.body = 'success'
},{name:'首页',group:'home'})


app.get('/cookie',async c=>{
    c.res.body = c.headers['cookie'] || '还没有设置cookie'
})

app.get('/login',async c=>{
    c.res.body = `<!DOCTYPE html><html>
        <head>
            <meta charset="utf-8">
        </head>
        <body>
            <form action="/login" method="post">
                <input type="text" name="username">
                <input type="password" name="passwd">
                <input type="submit" value="Login">
            </form>
        </body>
    </html>
    `
})

app.post('/login',async c=>{
    let {username,passwd} = c.body

    if(username === 'testuser' && passwd === '1234560'){
        c.setSession('is_login',true)
        //登录成功跳转首页
        c.status(301)
        c.setHeader('Location','/')
    }else{
        //登录失败跳转回登录页
        c.status(301)
        c.setHeader('Location','/login')        
    }
})

app.run(3001)